package org.lisen.mvc.tag;

import java.io.IOException;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.lisen.mvc.util.PageBean;

public class PagingTag extends BodyTagSupport {
	
	private PageBean pageBean;

	public PageBean getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}
	
	@Override
	public int doStartTag() throws JspException {
		
		JspWriter out = this.pageContext.getOut();
		
		try {
			out.println(buildHtml());
			return SKIP_BODY;
		} catch (IOException e) {
			throw new JspException("分页标签异常", e);
		}
		
	}
	
	//生成Html内容
	private String buildHtml() {
		
		//构建分页页面元素
		String pagingElement = "<div style=\"text-align: right; width:98%;\">\r\n" + 
				"		第"  + pageBean.getPage() + "页&nbsp;&nbsp;&nbsp;\r\n" + 
				"		共" + pageBean.getTotal() + "条记录&nbsp;&nbsp;&nbsp;\r\n" + 
				"		<a href=\"javascript: goPage(1);\">首页</a>&nbsp;&nbsp;&nbsp;\r\n" + 
				"		<a href=\"javascript: goPage('" + pageBean.getPreviousPage() + "');\">上页</a>&nbsp;&nbsp;&nbsp; \r\n" + 
				"		<a href=\"javascript: goPage('" + pageBean.getNextPage() + "');\">下页</a>&nbsp;&nbsp;&nbsp; \r\n" + 
				"		<a href=\"javascript: goPage('" + pageBean.getTotalPage() + "')\">尾页</a>&nbsp;&nbsp;&nbsp;\r\n" + 
				"		第<input type=\"text\" id=\"pagingPageNum\" size=\"2\" value='"+pageBean.getPage()+"' onkeypress=\"goSpecifiedPage(event,this.value);\"/> \r\n" + 
				"		<a href=\"javascript: goPage(document.getElementById('pagingPageNum').value)\">GO</a>\r\n" + 
				"	</div>";
		
		//构建隐藏表单，用于在分页时传递分页参数
		StringBuilder hiddenForm = new StringBuilder(
				"<form action='" + pageBean.getUrl() + "' id=\"pagingForm\" method=\"post\">"
				+ "<input type=\"hidden\" name=\"page\" />");
		Map<String, String[]> parameterMap = pageBean.getParameterMap();
		
		//分页时需要带所有的查询参数，但页码会变，所以需要排除
		for(Map.Entry<String, String[]> param: parameterMap.entrySet()) {
			String paramName = param.getKey();
			if("page".equals(paramName)) continue;
			String[] values = param.getValue();
			for(String val:  values) {
				hiddenForm.append("<input type='hidden' name='" + paramName + "' value='" + val + "'>");
			}
		}
		hiddenForm.append("</form>");
		
		//构建分页功能需要的js代码块
		String script = "<script>\r\n" + 
				"	function goPage(pageNum) {\r\n" + 
				"		var form = document.getElementById(\"pagingForm\");\r\n" + 
				"		form.page.value = pageNum;\r\n" + 
				"		form.submit();\r\n" + 
				"	}\r\n" + 
				"	\r\n" + 
				"	function goSpecifiedPage(event) {\r\n" + 
				"		if(event.keyCode == 13) {\r\n" + 
				"			var pageNum = document.getElementById(\"pagingPageNum\").value;\r\n" + 
				"			var form = document.getElementById(\"pagingForm\");\r\n" + 
				"			form.page.value = pageNum;\r\n" + 
				"			form.submit();\r\n" + 
				"		}\r\n" + 
				"	}\r\n" + 
				"	</script>";
		
		return pagingElement + hiddenForm + script;
	}
	

}
